package com.yq.master.annotation;


import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.remoting.caucho.HessianProxyFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Field;
import java.util.Map;

@Component
public class AzerothAutowiredProcessor implements BeanFactoryPostProcessor {

    private static Logger logger = LoggerFactory.getLogger(AzerothAutowiredProcessor.class);

    private String url = "http://localhost:8302/remote/";

    /**防止重复注册**/
    private Map<String, String> serviceMap = Maps.newHashMap();

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        logger.info("***** Service 自动配置开始**************************************************");

        String[] beanNames = beanFactory.getBeanNamesForAnnotation(Controller.class);

        for (String beanName : beanNames) {
            String className = beanFactory.getBeanDefinition(beanName).getBeanClassName();
            Class<?> clasz = null;
            try {
                clasz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new BeanInitializationException(e.getMessage(), e);
            }

            for(Field field : clasz.getDeclaredFields()) {
                if(!field.isAnnotationPresent(AzerothAutowired.class)) {
                    continue;
                }

                String fieldName = field.getName();

                // 检查 Service 是否已经注册
                if(serviceMap.get(fieldName)!=null) {
                    continue;
                }

                BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(HessianProxyFactoryBean.class);
                builder.getBeanDefinition().setAttribute("id", fieldName);
                builder.getBeanDefinition().setAttribute("class", "org.springframework.remoting.caucho.HessianProxyFactoryBean");

                builder.addPropertyValue("serviceUrl", url + fieldName);
                builder.addPropertyValue("serviceInterface", field.getType().getName());

                logger.info("bean id="+fieldName+" class=org.springframework.remoting.caucho.HessianProxyFactoryBean");
                logger.info("property name=serviceUrl value="+url + fieldName);
                logger.info("property name=serviceInterface value="+field.getType().getName());

                // 标记已经注册的 Service
                serviceMap.put(fieldName, field.getType().getName());

                logger.info("");

                ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(fieldName, builder.getBeanDefinition());

            }

        }

        logger.info("***** Service 自动配置结束**************************************************");
    }


}
